import _ from 'lodash';
import { writeFileSync, readFileSync } from "fs";
/**
 * 覆盖对象属性
 * @param distObject 初始化对象
 * @param srcObject 传递过来新对象
 */
export function mergeByFirst<T>(distObject: T, srcObject: Partial<T>) {
  const distPropList = _.keys(distObject);
  const srcPropList = _.keys(_.omitBy(srcObject, _.isNil));
  const propList = _.intersection(distPropList, srcPropList);
  return {
    ...distObject,
    ..._.pick(srcObject, propList),
  };
}

export function chunkFilePathName(filename: string, type: string = 'txt') {
  const prefix = process.env.ICAN_IGNORE_DIR
  return `${prefix}${filename}.${type}`
}

export function writeFileByType(filename: string, data: any, type: string = 'txt') {
  if (type === 'json') {
    writeFileSync(
      chunkFilePathName(filename, type),
      JSON.stringify(data, null, 2)
    );
  } else {
    data = data.toString();
    writeFileSync(
      chunkFilePathName(filename, type),
      data
    );
  }
}

export function readFileByType(filename: string, type: string = 'txt') {
  let data = null
  const prefix = process.env.ICAN_IGNORE_DIR
  if (type === 'json') {
    const json = readFileSync(
      chunkFilePathName(filename, type)).toString();
    data = JSON.parse(json)
  } else {
    data = readFileSync(
      chunkFilePathName(filename, type)).toString();
  }
  return data
}

export function jsonpToJson(datas: string) {
  if (!datas) return null;
  return JSON.parse(datas.substring(datas.indexOf("(") + 1, datas.lastIndexOf(")")));
}
